package com.gulimall.cart.interceptor;

import com.gulimall.common.constants.CartConstants;
import com.gulimall.common.vo.LoginInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author coder_ccy
 * @date 2022/4/2 17:07
 */
public class CartInterceptor implements HandlerInterceptor {


    public static ThreadLocal<LoginInfo>  loginInfoThreadLocal = new ThreadLocal<>();



    //1. 判断远程购物车还是本地购物车   2. 确保本地远程购物车都有一个key
    //  本地购物车，远程购物车都是放入redis
    //  远程购物车 key   id   本地购物车： key   userKey


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        LoginInfo loginInfo = (LoginInfo) session.getAttribute("loginInfo");

//        if(loginInfo!=null && loginInfo.getId()!=null){ // 远程购物车
//
//
//        }else{//本地购物车   key   gulimall_cart_user_key
//
//
//        }

        if(loginInfo==null)
        loginInfo = new LoginInfo();

        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if(CartConstants.GULIMALL_CART_USERKEY.equals(cookie.getName())){

                    loginInfo.setUserKey(cookie.getValue());
                    break;

                }
            }

        }



        if(StringUtils.isEmpty(loginInfo.getUserKey())){  // cookie中没有找到gulimall_cart_user_key   null.xx  null.xx()

            String uuid = UUID.randomUUID().toString();  //待会儿要添加到本地cookie
            loginInfo.setUserKey(uuid);
        }
        // loginInfo.id  loginInfo.userKey  肯定有一个   threadlocal 去存放用户信息


        loginInfoThreadLocal.set(loginInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        LoginInfo loginInfo = loginInfoThreadLocal.get();
        // 如果没有登录，将userkey存入 cookie

        if(loginInfo.getId()==null){  // 表示当前是离线用户，需要将userkey存入cookie

            Cookie cookie = new Cookie(CartConstants.GULIMALL_CART_USERKEY,loginInfo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstants.GULIMALL_CART_USERKEY_EXPIRETIME);  // 和session是一样的

            response.addCookie(cookie);


        }
    }
}
